#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cctype>

#include "general.h"
#include "Tracer.h"
#include "StreamRedirector.h"
#include "TraceFormatter.h"
#include "helpers.h"
#include "TestProtocol.h"
#include "ProtocolSerializer.h"
#include "ToPSyncFunctions.h"


using namespace std;

extern "C" void ProtocolSerializerSerialize(void);


// added comment

static std::ofstream fout;

int main(char* argv , int argc)
{  
  ToPSyncMsgHeader msgHeader;    

  /////////////////////////////////////////////
  // this is just some kind of test
  /** some lines to test the excpations of ofstream
  fout.exceptions ( std::ofstream::failbit | std::ofstream::badbit );

  try{
    if(fout.good()){
      fout << "pass" << endl;
      fout.flush();
    }
    fout.open("pp.txt");        
  }
  catch(std::ofstream::failure e){
    cout << "Exception opening/reading file: " << e.what();
  }
  if(fout.good()){
    fout << "pass" << endl;
    fout.flush();
    fout.close();
  }*/
  /////////////////////////////////////////////
  // SERIALIZER TEST

  InitSerializer("prot_out.txt");  

  SerializeSpiWriteByte(0x00, 0x80);

  unsigned char* wrPtr = mainBuff;
	InitialiseTopSyncMessageHeader(&msgHeader,
			             0xF1,
								   15,
								   2066,
								   1, 0, TRUE, 
								   0, 
								   0);
  
	WriteToPSyncMessageHeader(&wrPtr, &msgHeader);
  


  /////////////////////////////////////////////
  // some lines to test output redirection at run time
  std::cout << "Before redirect." << std::endl;
  std::ofstream filestream("tracerOut.txt");
  {
    StreamRedirector redirect(std::cout, filestream);
    std::cout << "During redirect." << std::endl;

    // yay:
    filestream << "also to the file, right?...yes" << std::endl;
    filestream << "i am not on the screen" << std::endl;
  }
  std::cout << "After redirect." << std::endl;

  Tracer t(filestream);
  string s = "My string";
  TraceFormatter tfs(s);

  // create binary data buffer
  char binbuff[20];
  for(int i =0; i <sizeof(binbuff)/sizeof(binbuff[0]); i++){
    binbuff[i]='A' + i;
  }
  /////////////////////////////////////////////

  tfs.FormatBinToHex((const unsigned char*)(binbuff),sizeof(binbuff)/sizeof(binbuff[0]));  
  t.Write(tfs.GetFormatted());

 

  ProtocolSerializer& ps = ProtocolSerializer::getInstance();
  ps.SetHeader(msgHeader);
  //ps.Serialize();

  fout << msgHeader;

  ProtocolSerializerSerialize();

  fout.close();
  return 0;
}